package com.cd.university.config.security.validate;

import com.cd.university.config.security.impl.SessionValidateCodeRepository;
import com.cd.university.config.security.validate.email.DefaultEmailCodeSender;
import com.cd.university.config.security.validate.email.EmailCodeSender;
import com.cd.university.config.security.validate.image.ImageCodeGenerator;
import com.cd.university.config.security.validate.sms.AliSmsCodeSender;
import com.cd.university.config.security.validate.sms.SmsCodeSender;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 注册验证码的bean，目的也是为了扩展，方便后面程序中替换使用新的验证码生成
 * @author 陈栋
 * @create 2021/9/4 11:09
 */
@Configuration
public class ValidateCodeBeanConfig {

    /**
     * Bean表示把imageCodeGenerator这个方法注入到Spring中
     * ConditionalOnMissingBean 表示如果容器中没有imageCodeGenerator这个bean才会生效
     * @return ValidateCodeGenerator实现类
     */
    @Bean
    @ConditionalOnMissingBean(name = "imageValidateCodeGenerator")
    public ValidateCodeGenerator imageValidateCodeGenerator() {
        ImageCodeGenerator codeGenerator = new ImageCodeGenerator();
        return codeGenerator;
    }

    /**
     * 默认使用session存储验证码
     * @return session类
     */
    @Bean
    @ConditionalOnMissingBean(name = "validateCodeRepository")
    public ValidateCodeRepository validateCodeRepository() {
        SessionValidateCodeRepository sessionValidateCodeRepository = new SessionValidateCodeRepository();
        return sessionValidateCodeRepository;
    }

    /**
     * 如果有实现类继承了EmailCodeSender接口那么邮件发送就会用邮件类，否则就是用默认邮件发送
     * @return 默认邮件发送类
     */
    @Bean
    @ConditionalOnMissingBean(EmailCodeSender.class)
    public EmailCodeSender emailCodeSender() {
        return new DefaultEmailCodeSender();
    }

    /**
     * 如果有实现类继承了SmsCodeSender接口那么短信发送就会使用新的继承类，否则就默认使用阿里云的发送
     * @return 阿里云的短信发送
     */
    @Bean("smsCodeSender")
    @ConditionalOnMissingBean(SmsCodeSender.class)
    public SmsCodeSender smsCodeSender() {
        return new AliSmsCodeSender();
    }
}
